package com.xxbb.chapter_11.dome4_packet;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.nio.charset.StandardCharsets;

public class Client extends Thread {
    private static DatagramSocket socket = null;
    private static InetAddress hostAddress = null;
    static final int PORT = 9090;
    private byte[] buf = new byte[1024];
    private DatagramPacket dp = new DatagramPacket(buf, buf.length);
    private int id;

    @Override
    public void run() {
        System.out.println("--客户端线程 id=" + id + "启动了--");
        for (int i = 0; i < 2; i++) {
            String outMessage = "线程 #" + id + "，消息 #" + i;
            //创建一数据报并发送
            try {
                socket.send(new DatagramPacket(outMessage.getBytes(), outMessage.getBytes().length, hostAddress, PORT));
                socket.receive(dp);//阻塞直到收到数据
                //获取数据包中的数据，转换成字符串
                String data = new String(dp.getData(), 0, dp.getLength(), StandardCharsets.UTF_8);
                String rcvd = "线程 " + id + "，收到：" + data;
                System.out.println(rcvd);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public Client(int identifier) {
        id = identifier;
        try {
            socket = new DatagramSocket();//创建socket对象
            hostAddress = InetAddress.getLocalHost();//获取本机端口
        } catch (Exception e) {
            System.err.println(e.getMessage());
            System.exit(0);
        }
    }
}
